package com.quectel.cms.controller.partyeducationtraining;


import cn.hutool.core.util.DesensitizedUtil;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partyeducationtraining.dto.TrainingCommentDto;
import com.quectel.core.module.partyeducationtraining.service.TrainingCommentService;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2022/05/07 16:40
 */
@RestController
@RequestMapping("trainingComment")
@Tag(name = "TrainingCommentController", description = "培训评价相关api")
public class TrainingCommentController extends BaseController {

    @DubboReference
    private TrainingCommentService trainingCommentService;

    /**
     * 导出列表
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "trainingComment:export")
    @Operation(summary = "导出评价列表")
    public void exportExcel(@RequestParam Map<String, Object> params,
                            HttpServletResponse resp) {
        //查询列表数据
        Request request = Request.configParamsNotPage(params)
                .like("personName")
                .like("personMobile");
        ;

        super.fillAuthorityData(params);
        List<TrainingCommentDto> list = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 10000);
        while (true) {
            params.put("offset", pageNo++ * 10000);
            List<TrainingCommentDto> trainingCommentDtos = trainingCommentService.queryList(params);
            if (CollectionUtils.isEmpty(trainingCommentDtos)) {
                break;
            }
            list.addAll(trainingCommentDtos);

        }
        String[] headers = new String[]{"所属园区", "培训课程", "评论人", "联系电话", "评分", "评价内容", "评论时间"};
        List<String[]> dataList = new ArrayList<>();
        for (TrainingCommentDto data : list) {
            String[] item = new String[headers.length];
            item[0] = data.getParty() == null ? "" : data.getParty().getName();
            item[1] = data.getTraining() == null ? "" : data.getTraining().getName();
            item[2] = data.getPartyPerson() == null ? "" : data.getPartyPerson().getName();
            item[3] = data.getPartyPerson() == null ? "" : data.getPartyPerson().getMobile();
            item[4] = data.getScore() == null ? "" : data.getScore().setScale(1, RoundingMode.HALF_UP).toPlainString();
            item[5] = data.getContent();
            item[6] = DateUtils.format(data.getCreateTime(), DateUtils.FormatType.COMMON);
            dataList.add(item);
        }
        POIUtils.exportExcel(resp, "评价信息", headers, dataList, "评价信息");

    }

    /**
     * 列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "trainingComment:list")
    @Operation(summary = "分页列表")
    public Response<Page<TrainingCommentDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = trainingCommentService.queryTotal(request.getParams());

        List<TrainingCommentDto> list = null;
        if (total > 0) {
            list = trainingCommentService.queryList(request.getParams());
            for (TrainingCommentDto trainingCommentDto : list) {
                PartyPersonDto partyPerson = trainingCommentDto.getPartyPerson();
                partyPerson.setName(DesensitizedUtil.chineseName(partyPerson.getName()));
                partyPerson.setMobile(DesensitizedUtil.mobilePhone(partyPerson.getMobile()));
            }
        } else {
            list = new ArrayList<>();
        }

        Page<TrainingCommentDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<TrainingCommentDto>>ok().wrap(page);
    }


    /**
     * 编辑反显查询
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "trainingComment:edit")
    @Operation(summary = "查询单条记录")
    public Response<TrainingCommentDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (trainingCommentService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        TrainingCommentDto trainingCommentDto = trainingCommentService.selectById(id);

        return Response.<TrainingCommentDto>ok().wrap((trainingCommentDto));
    }

    /**
     * 信息
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "trainingComment:info")
    @Operation(summary = "查询单条记录")
    public Response<TrainingCommentDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (trainingCommentService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        TrainingCommentDto trainingCommentDto = trainingCommentService.selectById(id);

        return Response.<TrainingCommentDto>ok().wrap((trainingCommentDto));
    }

    /**
     * 保存
     */
    @PostMapping("save")
    @RequirePermissions(values = "trainingComment:edit")
    @Operation(summary = "保存单条记录")
    public Response<Object> save(@RequestBody @Validated TrainingCommentDto trainingCommentDto) {

        //填充基础数据
        fillSaveCommonData(trainingCommentDto);

        trainingCommentService.save(trainingCommentDto);

        return Response.ok();
    }

    /**
     * 修改
     */
    @PostMapping("update")
    @RequirePermissions(values = "trainingComment:edit")
    @Operation(summary = "修改单条记录")
    public Response<Object> update(@RequestBody @Validated TrainingCommentDto trainingCommentDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(trainingCommentDto.getId()));
        if (trainingCommentService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(trainingCommentDto);

        trainingCommentService.updateById(trainingCommentDto);

        return Response.ok();
    }

    /**
     * 删除
     */
    @PostMapping("delete")
    @RequirePermissions(values = "trainingComment:delete")
    @Operation(summary = "批量删除记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (trainingCommentService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        trainingCommentService.deleteBatch(ids);

        return Response.ok();
    }
}
